package com.frozenc.controller.auth;

import com.alibaba.fastjson.JSON;
import com.frozenc.Util.CryptUtil;
import com.frozenc.domain.User;
import com.frozenc.enums.UserType;
import com.frozenc.mapper.UserMapper;
import org.postgresql.util.PSQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.*;

import static com.sun.org.apache.xalan.internal.xsltc.compiler.sym.error;

/**
 * Created by FrozenC on 2016/9/8.
 */
@Controller
public class SignUp {

    @Autowired
    UserMapper userMapper;

    @ModelAttribute
    public void setUser(HttpSession session, ModelMap modelMap){
        User user = (User) session.getAttribute("currUser");
        modelMap.addAttribute("currUser",user);
        return ;
    }

    @RequestMapping(value = "/signup",method = RequestMethod.GET)
    public String Get() {
        return "signup";
    }

    @RequestMapping(value = "/signup",method = RequestMethod.POST)
    @ResponseBody
    public String Post(@RequestBody @Valid User user, BindingResult result) {

        if (result.hasErrors()){
            result.getAllErrors().forEach(System.out::println);
            List<String> errorList = result.getAllErrors()
                    .stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.toList());
            return JSON.toJSONString(errorList);
        }

        user.setUserType(UserType.USER);
        user.setSalt(CryptUtil.getRandomSalt(6));
        user.setPassword(CryptUtil.getSHA1(user.getPassword(),user.getSalt()));

        try {
            userMapper.save(user);
        } catch (DataAccessException e) {
            String errMsg = e.getMessage();
            System.out.println(errMsg);
            if(errMsg.contains("username_check")){
                return "用户名已经被使用";
            }
            if(errMsg.contains("email_check")){
                return "邮箱已经被使用";
            }
            return "未知错误";
        }

        return "ok";
    }

}
